import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { authApi, SystemLoginRequest, AuthLoginResponse } from '../services/cloud/api/authApi';
import { RbacUtils } from '../services/cloud/api/rbacUtils';
import { message } from 'antd';
import type { User } from '../types/rbac';
import type { TenantUser } from '../types/tenant';

interface AuthState {
  // 状态
  isAuthenticated: boolean;
  user: User | null;
  token: string | null;
  isLoading: boolean;
  
  // 操作
  login: (loginData: SystemLoginRequest) => Promise<void>;
  logout: () => Promise<void>;
  updateUser: (user: Partial<User>) => void;
  hasPermission: (permission: string, context?: any) => boolean;
  hasRole: (role: string) => boolean;
  refreshToken: () => Promise<void>;
  getCurrentUser: () => Promise<void>;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      // 初始状态
      isAuthenticated: false,
      user: null,
      token: null,
      isLoading: false,

      // 系统用户登录
      login: async (loginData: SystemLoginRequest) => {
        try {
          const response: AuthLoginResponse = await authApi.systemLogin(loginData);
          console.log('Login response:', response);
          
          // 存储token到localStorage
          localStorage.setItem('token', response.accessToken);
          
          // 只存储必要的用户信息，避免复杂的数据转换
          const user: User = {
            id: response.userId,
            username: response.username,
            email: response.email,
            realName: response.username,
            avatar: response.avatar || '',
            phone: response.phone || '',
            status: response.status,
            gender: response.gender || 0,
            age: response.age || 0,
            description: response.description || '',
            roles: [], // 菜单加载时会通过API获取
            teams: [], // 菜单加载时会通过API获取
            departments: [], // 菜单加载时会通过API获取
            permissions: [], // 菜单加载时会通过API获取
            menus: [], // 菜单加载时会通过API获取
            lastLoginTime: response.loginTime || '',
            createTime: response.loginTime || new Date().toISOString(),
            updateTime: response.loginTime || new Date().toISOString()
          };
          
          // 更新状态
          set({
            isAuthenticated: true,
            user: user,
            token: response.accessToken,
          });
          
          // 调试信息
          console.log('Token stored:', localStorage.getItem('token'));
          console.log('Auth state updated:', {
            isAuthenticated: true,
            user: user,
            hasToken: !!response.accessToken
          });
          console.log('系统用户登录成功:', {
            userId: user.id,
            username: user.username,
            isSuperAdmin: response.superAdmin === 1,
            syncedToTenantStore: true
          });
          
          message.success('登录成功！');
        } catch (error) {
          console.error('Login error:', error);
          message.error('登录失败，请检查用户名和密码');
          throw error;
        }
      },

      // 登出
      logout: async () => {
        try {
          await authApi.logout();
        } catch (error) {
          console.error('登出API调用失败:', error);
        } finally {
          // 无论API调用成功与否，都清除本地状态
          localStorage.removeItem('token');
          localStorage.removeItem('user');
          set({
            isAuthenticated: false,
            user: null,
            token: null,
          });
        }
      },

      // 刷新令牌
      refreshToken: async () => {
        const { token } = get();
        if (!token) {
          throw new Error('无刷新令牌');
        }
        
        try {
          const response = await authApi.refreshToken({ refreshToken: token });
          localStorage.setItem('token', response.accessToken);
          
          // 将后端扁平化的用户数据转换为前端期望的User对象
          const user: User = {
            id: response.userId,
            username: response.username,
            email: response.email,
            realName: response.username,
            avatar: response.avatar || '',
            phone: response.phone || '',
            status: response.status,
            gender: response.gender || 0,
            age: response.age || 0,
            description: response.description || '',
            roles: [],
            teams: [],
            departments: response.departmentId ? [{ 
              id: response.departmentId, 
              name: '', 
              code: '', 
              parentId: undefined, 
              level: 0, 
              sort: 0, 
              status: 1, 
              createTime: '', 
              updateTime: '' 
            }] : [],
            permissions: [],
            menus: [],
            lastLoginTime: response.loginTime || '',
            createTime: response.loginTime || new Date().toISOString(),
            updateTime: response.loginTime || new Date().toISOString()
          };
          
          set({
            token: response.accessToken,
            user: user,
          });
        } catch (error) {
          // 刷新失败，清除状态
          get().logout();
          throw error;
        }
      },

      // 获取当前用户信息
      getCurrentUser: async () => {
        try {
          const user = await authApi.getCurrentUser();
          set({ user });
        } catch (error) {
          console.error('获取用户信息失败:', error);
          throw error;
        }
      },

      // 更新用户信息
      updateUser: (userData: Partial<User>) => {
        const { user } = get();
        if (user) {
          set({
            user: { ...user, ...userData },
          });
        }
      },

      // 检查权限（支持上下文）
      hasPermission: (permission: string, context?: any) => {
        const { user } = get();
        if (!user) return false;
        
        // 使用适配的权限检查方法
        return RbacUtils.hasPermissionAdapted(user, permission);
      },

      // 检查角色
      hasRole: (role: string) => {
        const { user } = get();
        if (!user) return false;
        
        // 使用适配的角色检查方法
        return RbacUtils.hasRoleAdapted(user, role);
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({
        isAuthenticated: state.isAuthenticated,
        user: state.user,
        token: state.token,
      }),
    }
  )
);